import AntModal from '@/components/pt/dialog/AntModal'
import AdvanceTable from '@/components/pt/table/AdvanceTable'
import BizProduct from '@/views/biz/bizorder/modules/BizProduct'
import { getBizOrder, addBizOrder, updateBizOrder, auditOrder, delBizOrder, installOrder, spplementBizOrder,checkAddressUnique } from '@/api/biz/bizOrder'
import { upload } from '@/api/system/upload'
import SelectUser from '@/components/pt/selectUser/SelectUser'
import BizProjectForm from './BizProjectForm';
import storage from 'store'
import { ACCESS_TOKEN } from '@/store/mutation-types'
import { listBizWarehouseSpaceByproductId } from '@/api/biz/bizWarehouseSpace'
import { getBizCustomer } from '@/api/biz/bizCustomer'
import { listBizProductInventory } from "@/api/biz/bizProductInventory"
import { allListBizWarehouseByProductId } from '@/api/biz/bizWarehouse'
import { randomUUID } from '@/utils/util'
import tableDragResizeMixin from '@/mixins/tableDragResizeMixin'
import { hasPermi,getColor } from '@/utils/util';
import moment from 'moment';
import { listBizProject } from '@/api/biz/bizProject'
export default {
  name: 'CreateForm',
  mixins: [tableDragResizeMixin],
  props: {
    customerIdOptions: {
      type: Array,
      required: false
    },
    warehouseIdOptions: {
      type: Array,
      required: false
    },
    isSettleSendOptions: {
      type: Array,
      required: false
    },
    orderTypeOptions: {
      type: Array,
      required: false
    },
    installOptions: {
      type: Array,
      required: false
    },
    deliveryOptions: {
      type: Array,
      required: false
    },
  },
  components: {
    AntModal,
    SelectUser,
    BizProduct,
    AdvanceTable,
    BizProjectForm
  },
  data() {
    return {
      showProductModal: false,
      showPlanModal: false,
      disabledCreated: true,//禁用mixin的created
      activeKey: "1",
      uploadUrl: process.env.VUE_APP_BASE_API + "/common/upload",
      // 设置上传的请求头部
      headers: { Authorization: 'Bearer ' + storage.get(ACCESS_TOKEN) },
      multiple: false,
      multipleDetail: false,
      open: false,
      closeDialog: true,
      spinning: false,
      handleTimer:null,
      delayTime: 100,
      labelCol: {
        xs: { span: 24 },
        sm: { span: 8 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 },
      },
      loading: false,
      disabled: true,
      disabledSubmit: false,//禁用提交
      total: 0,
      id: undefined,
      formTitle: '添加销售单',
      // 表单参数
      form: { orderType: "1"},
      attachmentRefName: 'addUploaderFile', // 标志表单是否含有附件
      formId: '',
      spaceList: [],//仓位
      productList: [],//订单明细
      materialList: [],//物料明细
      currentType: '',//当前新增明细类型
      projectList:[],//项目列表
      cannotEdit:false,
      isRepet:false,
      rules: {
        customerId: [{ required: true, message: '客户不能为空', trigger: 'blur' }],
        orderType: [{ required: true, message: '订单类型不能为空', trigger: 'blur' }],
        deliveryType: [{ required: true, message: '请选择配送模式', trigger: 'blur' }],
        installType: [{ required: true, message: '请选择安装模式', trigger: 'blur' }],
      },
      columns: [
        {
          title: '排序',
          dataIndex: 'sort',
          ellipsis: true,
          align: 'left',
          width: '12.8%',
          scopedSlots: {
            customRender: 'sort'
          }
        },
        {
          title: '操作',
          dataIndex: 'operate',
          ellipsis: true,
          width: '12.8%',
          scopedSlots: {
            customRender: 'operate'
          }
        },
        {
          title: '区域',
          dataIndex: 'area',
          ellipsis: true,
          align: 'left',
          width: '12.8%',
          scopedSlots: { customRender: 'areaSlot' }
        },
        {
          title: '产品编号',
          dataIndex: 'productCode',
          ellipsis: true,
          align: 'left',
          width: '12.8%'
        },
        {
          title: '型号',
          dataIndex: 'model',
          align: 'right',
          width: '12.8%'
        },
        {
          title: '颜色',
          dataIndex: 'color',
          align: 'center',
          width: '8%'
        },
        {
          title: '规格',
          dataIndex: 'spec',
          align: 'center',
          width: '8%'
        },
        {
          title: '品牌',
          dataIndex: 'brand',
          align: 'center',
          width: '8%'
        },
        {
          title: '数量',
          dataIndex: 'number',
          align: 'right',
          width: '12.8%',
          scopedSlots: {
            customRender: 'numberSlot'
          }
        },
        {
          title: '系数',
          dataIndex: 'coefficient',
          align: 'right',
          width: '12.8%',
          scopedSlots: { customRender: 'coefficientSlot' }
        },
        {
          title: '单价',
          dataIndex: 'price',
          align: 'right',
          width: '12.8%',
          scopedSlots: { customRender: 'priceSlot' }
        },
        {
          title: '单位',
          dataIndex: 'unit',
          align: 'right',
          width: '12.8%',
          scopedSlots: {
            customRender: 'unitSlot'
          }
        },
        {
          title: '金额',
          dataIndex: 'amount',
          align: 'right',
          width: '12.8%',
          scopedSlots: { customRender: 'amountSlot' }
        },
        {
          title: '备注',
          dataIndex: 'remark',
          align: 'center',
          width: '8%',
          scopedSlots: { customRender: 'remarkSlot' }
        },
        // {
        //   title: '操作',
        //   dataIndex: 'operation',
        //   align: 'center',
        //   width: '10%',
        //   scopedSlots: { customRender: 'operation' }
        // }
      ],
      columns1: [
        {
          title: '工序计划',
          ellipsis: true,
          dataIndex: 'planId',
          align: 'center',
          width: '15%',
          scopedSlots: {
            customRender: 'planSlot'
          }
        },
        {
          title: '产品编号',
          dataIndex: 'productCode',
          ellipsis: true,
          align: 'center',
        },
        {
          title: '型号',
          dataIndex: 'model',
          align: 'center',
          width: '8%'
        },
        {
          title: '数量',
          dataIndex: 'number',
          align: 'center',
          width: '8%'
        },
        {
          title: '单价',
          dataIndex: 'price',
          align: 'center',
          width: '8%'
        },
        {
          title: '单位',
          dataIndex: 'unit',
          align: 'center',
          width: '8%'
        },
        {
          title: '金额',
          dataIndex: 'amount',
          align: 'center',
          scopedSlots: {
            customRender: 'amountSlot'
          }
        },
        {
          title: '操作',
          dataIndex: 'operation',
          align: 'center',
          width: '10%',
          scopedSlots: { customRender: 'operation' }
        }
      ],
      columns2: [
        {
          title: '操作',
          dataIndex: 'operate',
          ellipsis: true,
          width: '12.8%',
          scopedSlots: {
            customRender: 'operate'
          }
        },
        {
          title: '产品编号',
          dataIndex: 'productCode',
          ellipsis: true,
          align: 'left',
          width: '12.8%'
        },
        {
          title: '型号',
          dataIndex: 'model',
          align: 'right',
          width: '12.8%'
        },
        {
          title: '颜色',
          dataIndex: 'color',
          align: 'right',
          width: '12.8%'
        },
        {
          title: '规格',
          dataIndex: 'spec',
          align: 'right',
          width: '12.8%'
        },
        {
          title: '品牌',
          dataIndex: 'brand',
          align: 'right',
          width: '12.8%'
        },
        {
          title: '仓库',
          dataIndex: 'warehouseId',
          align: 'right',
          width: '12.8%',
          scopedSlots: {
            customRender: 'warehouseSlot'
          }
        },
        {
          title: '仓位',
          dataIndex: 'spaceId',
          align: 'right',
          width: '12.8%',
          scopedSlots: {
            customRender: 'spaceSlot'
          }
        },
        {
          title: '库存',
          dataIndex: 'stock',
          align: 'right',
          width: '12.8%'
        },
        {
          title: '数量(片)',
          dataIndex: 'number',
          align: 'right',
          width: '12.8%',
          scopedSlots: {
            customRender: 'number2Slot'
          }
        },
        {
          title: '数量(米)',
          dataIndex: 'number3',
          align: 'right',
          width: '12.8%'
        },
        {
          title: '数量(平米)',
          dataIndex: 'number4',
          align: 'right',
          width: '12.8%'
        },
        {
          title: '备注',
          dataIndex: 'productType',
          align: 'right',
          width: '12.8%',
          scopedSlots: {
            customRender: 'productType'
          }
        }
      ],
      columns3: [
        {
          title: '产品编号',
          dataIndex: 'productCode',
          ellipsis: true,
          align: 'center',
        },
        {
          title: '型号',
          dataIndex: 'model',
          align: 'center',
          width: '8%'
        },
        {
          title: '数量',
          dataIndex: 'number',
          align: 'center',
          width: '8%'
        },
        {
          title: '单价',
          dataIndex: 'price',
          align: 'center',
          width: '8%',
        },
        {
          title: '单位',
          dataIndex: 'unit',
          align: 'center',
          width: '8%'
        },
        {
          title: '金额',
          dataIndex: 'amount',
          align: 'center',
          scopedSlots: {
            customRender: 'amountSlot'
          }
        },
        {
          title: '操作',
          dataIndex: 'operation',
          align: 'center',
          width: '10%',
          scopedSlots: { customRender: 'operation' }
        }
      ],
      list: [],
      selectedRowKeys: [],
      selectedDetailRowKeys: [],
      selectedDetailRows: [],
      ids: [],
      fileList: []
    }
  },
  filters: {},
  created() {
    this.initColumnsSetting('productDetail', 'columns')
    this.initColumnsSetting('materialDetail', 'columns2')
  },
  computed: {},
  // watch: {
  //   productList:{
  //     handler(newValue, oldValue) {
  //       console.log('newValue :>> ', newValue);
  //     },
  //   },
  //   materialList(newValue, oldValue) {
  //     console.log('newValue :>> ', newValue);
  //   },
  // },
  mounted() { },
  methods: {
    hasPermi,
    onClose() {
      this.open = false
      this.reset()
      this.$emit('close')
    },
    // 取消按钮
    cancel() {
      console.log('cancel')
      this.open = false
      this.reset()
      this.$emit('close')
    },
    // 表单重置
    reset() {
      this.form = {
        id: undefined,
        orderNumber: undefined,

        customerId: undefined,

        orderDate: undefined,

        address: undefined,

        phone: undefined,

        installDate: undefined,

        biller: undefined,

        receiveDate: undefined,

        isSettleSend: undefined,

        orderType: "1",

        remark: undefined,
        remarkA: undefined,
        remarkB: undefined

      }
      this.materialList = []
      this.productList = []
      this.fileList = []
      this.selectedRowKeys = []
    },
    spaceFocus(record, index) {
      if (!record.warehouseId) return
      listBizWarehouseSpaceByproductId(record.warehouseId, record.productId).then(res => {
        record.spaceList = res.data;
        this.materialList.splice(index, 1, record)
      });
    },
    warehouseFocus(record, index) {
      allListBizWarehouseByProductId(record.productId).then(res => {
        record.warehouseIdOptions = res.data
        record.uuid = randomUUID()
        this.materialList.splice(index, 1, record)
      })
    },
    selectWarehouse(record, index) {
      if (!record.warehouseId) {
        return;
      }
      listBizWarehouseSpaceByproductId(record.warehouseId, record.productId).then(res => {
        record.spaceList = res.data;
        record.spaceId = ''
        this.materialList.splice(index, 1, record)
      });
    },
    /**
     * 排序
     * @param {obj} record 
     * @param {number} index 
     * @param {number} type 1.up,2.down
     */
    sort(record,index,type){
      if(type == 1){
        if(index > 0){
          let item = this.productList[index - 1]
          this.productList.splice(index-1,2,record,item)
        }
      }else{
        if(index < this.productList.length - 2){
          let item = this.productList[index + 1]
          this.productList.splice(index,2,item,record)
        }
      }
    },
    /**
     * @param {string} value 
     * @param {obj} record 
     * @param {number} index 
     */
    selectSpace(value, record, index) {
      record.spaceId = value

      let params = {
        warehouseId: record.warehouseId,
        productId: record.productId,
        spaceId: value
      }
      listBizProductInventory(params).then(res => {
        let data = res.data.list
        if (data.length === 0) {
          record.stock = 0
          this.materialList.splice(index, 1, record)
        } else if (data.length === 1) {
          record.stock = data[0].number
          this.materialList.splice(index, 1, record)
        } else {
          console.log('库存异常 :>> ');
        }
      })
    },
    
    /** 关联测量单新增按钮操作 */
    handleMeasureAdd(row) {
      this.reset()
      this.open = true
      this.formTitle = '新增销售单';
      this.form.billerObj = { ids: row.measurer, names: row.measurerName }
      this.form.measureId = row.id
      this.cannotEdit = !this.hasPermi('biz:bizOrder:auditedEdit')
      
      this.disabled = false
      console.log('this.cannotEdit :>> ', this.cannotEdit);
      if (row.measureDate) {
        this.$set(this.form,'receiveDate',moment(new Date(row.measureDate)).format('YYYY-MM-DD'))
      }
      this.form.address = row.address
      this.form.phone = row.phone
      this.$forceUpdate()
    },
    /** 新增按钮操作 */
    handleAdd(row) {
      this.reset()
      this.open = true
      this.formTitle = row.id ? '修改销售单' : '新增销售单';
      this.form = row
      
      this.addressChange({target:{value:this.form.address}})
      if (row.id) {
        this.loading = true
        getBizOrder(row.id).then(res => {
          this.loading = false
          if (res.code == 200) {
            this.form = res.data
            this.cannotEdit = !this.hasPermi('biz:bizOrder:auditedEdit') && this.form.auditStatus > 1
            this.form.billerObj = { ids: row.biller, names: row.billerName }
            this.form.customernanObj = { ids: row.customernan, names: row.customernanName }
            this.form.projectNumber = this.form.projectNumber || row.projectNumber
            this.form.attachList = this.form.attachList || []
            this.form.attachList.forEach((item, index) => {
              const d = {
                uid: index,
                name: item,
                url: item,
                status: 'done'
              }
              // 文件列表
              this.fileList.push(d)
            })
            this.productList = this.form.productList.map(v => {
              v.unitList = []
              v.unit = +v.unit
              v.salePrice = v.bizProduct.salePrice
              v.productCode = v.bizProduct.productCode
              v.model = v.bizProduct.model
              v.color = v.bizProduct.color
              v.brand = v.bizProduct.brand
              v.spec = v.bizProduct.spec
              v.coefficient = v.coefficient || 1,
              v.rowKey = randomUUID()
              v.unitList.push({
                key: 1,
                name: v.bizProduct.unit
              })
              v.unitList.push({
                key: 2,
                name: v.bizProduct.assistUnitA
              })
              v.unitList.push({
                key: 3,
                name: v.bizProduct.assistUnitB
              })
              return v
            })
            console.log('this.productList :>> ', this.productList);
            this.materialList = this.form.materialList.map(v => {
              v.spaceList = [{ postion: v.spaceName, id: v.spaceId }]
              v.warehouseIdOptions = [{ warehouseName: v.warehouseName, id: v.warehouseId }]
              return v
            })
            console.log(this.materialList, 'materialList');
            this.countTotal()
          } else {
            this.$message.error(res.msg)
          }
        })

      } else {
        this.disabled = false
        // 默认日期
        this.$set(this.form,'receiveDate',moment(new Date()).format('YYYY-MM-DD'))
      }
      this.$set(this.form, 'orderType', '1')
      this.$set(this.form, 'deliveryType', '2')
      this.$set(this.form, 'installType', '2')
    },
    handleEdit(record) {
      this.handleAdd(record)
      this.disabled = false
    },
    modify() {
      this.disabled = false

    },
    audit(row, status) {
      var that = this
      that.$confirm({
        title: `确认${status == 1 ? '反' : ''}审核所选中数据?`,
        onOk() {
          return auditOrder(row.id, status).then((res) => {
            if (res.code === 200) {
              that.$message.success('更新成功', 3)
              that.$emit('ok', row)

              that.open = false
              that.$emit('close')
              // if(status == 1){
              //   that.form.auditStatus = '1'
              //   that.disabled = false
              //   that.form.version += 1 
              // }else{
              // }
            }
          })
        },
        onCancel() { },
      })
    },
    handleSupplement(row) {
      this.disabled = false
      this.reset()
      this.open = true
      this.formTitle = '销售单补单';
      this.form = row
      if (row.id) {
        this.loading = true
        getBizOrder(row.id).then(res => {
          this.loading = false
          if (res.code == 200) {
            this.cannotEdit = !this.hasPermi('biz:bizOrder:auditedEdit') && this.form.auditStatus > 1
            this.form.billerObj = { ids: row.biller, names: row.billerName }
            this.form.attachList = res.data.attachList || []
            this.form.productList = res.data.productList || []
            this.form.materialList = res.data.materialList || []
            this.form.attachList.forEach((item, index) => {
              const d = {
                uid: index,
                name: item,
                url: item,
                status: 'done'
              }
              // 文件列表
              this.fileList.push(d)
            })
            this.productList = this.form.productList.map(v => {
              v.unitList = []
              v.unit = +v.unit
              v.salePrice = v.bizProduct.salePrice
              v.productCode = v.bizProduct.productCode
              v.model = v.bizProduct.model
              v.color = v.bizProduct.color
              v.brand = v.bizProduct.brand
              v.spec = v.bizProduct.spec
              v.coefficient = v.coefficient || 1
              v.unitList.push({
                key: 1,
                name: v.bizProduct.unit
              })
              v.unitList.push({
                key: 2,
                name: v.bizProduct.assistUnitA
              })
              v.unitList.push({
                key: 3,
                name: v.bizProduct.assistUnitB
              })
              return v
            })
            console.log('this.productList :>> ', this.productList);
            this.materialList = this.form.materialList.map(v => {
              v.spaceList = [{ postion: v.spaceName, id: v.spaceId }]
              v.warehouseIdOptions = [{ warehouseName: v.warehouseName, id: v.warehouseId }]
              return v
            })
            console.log(this.materialList, 'materialList');
            this.countTotal()
          } else {
            this.$message.error(res.msg)
          }
        })
      }
    },
    /** 提交按钮 */
    submitForm: function (closeDialog) {
      this.closeDialog = closeDialog
      let materialList = this.materialList.filter(v => v[this.columns2[0].dataIndex] !== '合计');
      let flag = materialList.some(val=>!val.warehouseId)
      if(this.form.orderType === '3' && flag){
        this.$message.error('请选择物料仓库')
        return 
      }
      this.disabledSubmit = true
      this.$refs.form.validate(valid => {
        if (valid) {
          const saveForm = JSON.parse(JSON.stringify(this.form))
          saveForm.attachList = [];
          this.fileList.forEach(item => {
            saveForm.attachList.push(item.url);
          })
          if (this.form.billerObj !== undefined) {
            saveForm.biller = this.form.billerObj.ids
          }
          if (this.form.billerObj !== undefined) {
            saveForm.customernan = this.form.customernanObj.ids
          }
          saveForm.productList = this.productList.filter(v => v[this.columns[0].dataIndex] !== '合计');
          saveForm.productList = saveForm.productList.map((v,i)=>(v.sort = i,v))
          saveForm.materialList = this.materialList.filter(v => v[this.columns2[0].dataIndex] !== '合计');
          saveForm.materialList = saveForm.materialList.map((v,i)=>(v.sort = i,v))
          saveForm.shippingStatus = 0//未发货
          if (this.form.id !== undefined) {
            updateBizOrder(saveForm).then(response => {
              this.$message.success('更新成功', 3)
              this.open = false
              this.$emit('ok')
              this.$emit('close')
              this.disabledSubmit = false
            }).catch(()=>{
              this.disabledSubmit = false
            })
          } else {
            addBizOrder(saveForm).then(response => {
              this.$message.success('新增成功', 3)
              this.open = false
              this.$emit('ok')
              this.$emit('close')
              this.disabledSubmit = false
            }).catch(()=>{
              this.disabledSubmit = false
            })
          }
        } else {
          this.disabledSubmit = false
          return false
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      var that = this
      that.$confirm({
        title: '确认删除所选中数据?',
        onOk() {
          return delBizOrder(row.id).then(() => {
            that.open = false
            that.$emit('ok')
            that.$emit('close')
            that.disabled = false
          })
        },
        onCancel() { },
      })
    },
    submitSupplement: function (closeDialog) {
      this.closeDialog = closeDialog
      this.disabled = true
      this.$refs.form.validate(valid => {
        if (valid) {
          const saveForm = JSON.parse(JSON.stringify(this.form))
          saveForm.attachList = [];
          this.fileList.forEach(item => {
            saveForm.attachList.push(item.url);
          })
          if (this.form.billerObj !== undefined) {
            saveForm.biller = this.form.billerObj.ids
          }
          saveForm.productList = this.productList;
          saveForm.materialList = this.materialList;
          spplementBizOrder(saveForm).then(response => {
            this.$message.success('补单成功', 3)
            this.open = false
            this.$emit('ok')
            this.$emit('close')
            this.disabled = false
          })
        } else {
          this.disabled = false
          return false
        }
      })
    },
    submitInstall: function (closeDialog) {
      console.log('this.form :>> ', this.form);
      // {userId:id,orderId:this.orderId,installerType:this.installerType}
      // 安装数据
      if (this.form.userId) {
        userIds = this.form.userId.ids.split(';')
        names = this.form.userId.names.split(';')
      }
      return;
      this.closeDialog = closeDialog
      this.disabled = true
      this.$refs.form.validate(valid => {
        if (valid) {
          const saveForm = JSON.parse(JSON.stringify(this.form))
          saveForm.userList = [];
          if (this.form.userId !== undefined) {
            let ids = this.form.userId.ids.split(";");
            ids.forEach(item => {
              saveForm.userList.push(item);
            })
          }
          installOrder(saveForm).then(response => {
            this.$message.success('操作成功', 3)
            this.open = false
            this.$emit('ok')
            this.$emit('close')
            this.disabled = false
          })
        } else {
          this.disabled = false
          return false
        }
      })
    },
    selectPlan(record) {
      this.showPlanModal = true
      this.$nextTick(() => {
        this.$refs.bizOrderPlanForm.handlePlan(record);
      })
    },
    back() {
      const index = '/biz/bizorder/index'
      this.$router.push(index)
    },
    getCheckboxProps(record) {
      // 禁用合计以及已审核状态下参与库存计算的产品
      let flag = record[this.columns[0].dataIndex] === '合计' || (record.bizProduct && record.bizProduct.inventoryFlag !== '0' && this.form.auditStatus > 1)
      return { props: { disabled: flag } }
    },
    getMaterialCheckboxProps(record) {
      return { props: { disabled: record[this.columns2[0].dataIndex] === '合计' } }
    },
    changeAmount(row,index){
      if(row.amount && row.number){
        row.price = (row.amount / row.number).toFixed(2)
      }
      this.productList.splice(index,1,row)
      this.countTotal()
    },
    /**
     * 地址change
     * @param {string} value 
     */
    addressChange(e){
      let param = {
        id:this.form.id || '',
        address:e.target.value
      }
      checkAddressUnique(param).then(res=>{
        this.isRepet = res
      })
    },
    onSelectChange(selectedRowKeys, selectedRows) {
      this.selectedRowKeys = selectedRowKeys
      this.selectedRows = selectedRows
      this.ids = this.selectedRows.map(item => item.id)
      this.single = selectedRowKeys.length == 1
      this.multiple = selectedRowKeys.length
    },
    
    onSelect: (record, selected, selectedRows) => {
      console.log(record, selected, selectedRows);
    },
    onSelectDetailChange(selectedDetailRowKeys, selectedRows) {
      this.selectedDetailRowKeys = selectedDetailRowKeys
      this.selectedDetailRows = selectedRows
      this.multipleDetail = selectedDetailRowKeys.length
    },
    handleViewById(id) {
      this.reset();
      this.open = true
      this.disabled = true
      this.formTitle = '查看销售单';
      this.form.auditStatus=0;
      this.form.view=true;
      this.disabled = true;
      this.addressChange({target:{value:this.form.address}})
      getBizOrder(id).then((res)=>{
        res.data.auditStatus=0;
        this.form = {...this.form,...res.data};
        this.form.billerObj = { ids: res.data.biller, names: res.data.billerName }
        this.materialList = res.data.materialList
        // .map(v=>{
        //   v.warehouseIdOptions =
        // })
        this.productList = res.data.productList.map(item => {
          item.unitList = [];
          item.unitList.push({
            key: 1,
            name: item.unit
          })
          item.unitList.push({
            key: 2,
            name: item.assistUnitA
          })
          item.unitList.push({
            key: 3,
            name: item.assistUnitB
          })
          return item
        })

        // 处理column
        const handleColumn = (columns, matchStr, dataIndex) => {
          let index = columns.findIndex(v => v.dataIndex === matchStr)
          if (index > -1) {
            columns[index].dataIndex = dataIndex
            delete columns[index].scopedSlots
          }
          return columns
        }
        this.columns2 = handleColumn(this.columns2, 'warehouseId', 'warehouseName')
        this.columns2 = handleColumn(this.columns2, 'spaceId', 'spaceName')
      })

    },
   /* handleView(record) {
      this.reset()
      this.open = true
      this.disabled = true
      this.formTitle = '查看销售单';
      this.form = record
      this.form.billerObj = { ids: record.biller, names: record.billerName }
      this.materialList = record.materialList
      // .map(v=>{
      //   v.warehouseIdOptions = 
      // })
      this.productList = record.productList.map(item => {
        item.unitList = [];
        item.unitList.push({
          key: 1,
          name: item.unit
        })
        item.unitList.push({
          key: 2,
          name: item.assistUnitA
        })
        item.unitList.push({
          key: 3,
          name: item.assistUnitB
        })
        return item
      })

      // 处理column
      const handleColumn = (columns, matchStr, dataIndex) => {
        let index = columns.findIndex(v => v.dataIndex === matchStr)
        if (index > -1) {
          columns[index].dataIndex = dataIndex
          delete columns[index].scopedSlots
        }
        return columns
      }
      this.columns2 = handleColumn(this.columns2, 'warehouseId', 'warehouseName')
      this.columns2 = handleColumn(this.columns2, 'spaceId', 'spaceName')
    },*/

    handleView(record) {
      this.handleAdd(record)
      if (record.auditStatus === '1') {
        this.disabled = false
      } else if (record.auditStatus === '2') {
        this.disabled = true
      }
    },
    handleInstall(record) {
      this.reset()
      this.open = true
      this.formTitle = '指定安装员';
      this.form = record
    },
    handleDeleteRows() {
      if (!this.selectedRowKeys.length) {
        this.$message.error(
          '请选择要删除的数据',
          3
        )
        return
      }
      this.$confirm({
        title: '确认删除所选中数据?',
        onOk: () => {
          this.productList = this.productList.filter((v, index) => !this.selectedRowKeys.includes(index) && !this.selectedRowKeys.includes(v.rowKey))
          this.selectedRowKeys = []
          this.multiple = false
          this.$message.success(
            '删除成功',
            3
          )
        }
      })
    },
    handleDeleteDetailRows() {
      this.$confirm({
        title: '确认删除所选中数据?',
        onOk: () => {
          this.materialList = this.materialList.filter((v, index) => !this.selectedDetailRowKeys.includes(index) && !this.selectedDetailRowKeys.includes(v.id))
          this.selectedDetailRowKeys = []
          this.multipleDetail = false
          this.$message.success(
            '删除成功',
            3
          )
        }
      })
    },
    handleSubDelete(row) {
      var that = this
      const productIds = row.id || this.ids
      this.$confirm({
        title: '确认删除所选中数据?',
        onOk() {
          let selectedList = JSON.parse(JSON.stringify(that.list));
          selectedList.forEach((item, index) => {
            if (row.id) {
              that.list = that.list.filter(item => item.id != row.id)
              return;
            } else {
              that.selectedRows.forEach(item2 => {
                that.list = that.list.filter(item => item.id != item2.id)
                return;
              })
            }
          })
          that.$message.success(
            '删除成功',
            3
          )
          that.onSelectChange([], [])
          return;
        },
        onCancel() { }
      })
    },
    handleAddProduct(type) {
      this.currentType = type
      this.showProductModal = true
      this.$nextTick(() => {
        if(type === 'productList'){
          if(+this.form.auditStatus > 1){
            this.$refs.bizProduct.queryParam.inventoryFlag = 0

          }else{
            this.$refs.bizProduct.queryParam.inventoryFlag = null
          }
        }else{
          this.$refs.bizProduct.queryParam.inventoryFlag = 1
        }
        this.$refs.bizProduct.handleAddProduct(this.list);
      })
    },
    selectProduct(selectedRows) {
      let flag = false
      //修改单位
      let productList = []
      let materialList = []
      selectedRows.forEach(item => {
        item.number = 0;
        item.coefficient = 1
        item.tempSalePrice = item.salePrice;
        item.warehouseIdOptions = []
        if (item.defaultOutboundUnit == 2) {
          item.number = item.number * item.convertRatioA;
          item.salePrice = item.salePriceA
        } else if (item.defaultOutboundUnit == 3) {
          item.salePrice = item.salePriceB
          item.number = item.number * item.convertRatioB;
        } else {
          item.number = item.number;
        }
        item.amount = 0.00;
        item.rowKey = randomUUID()
        item.unitList = [];
        item.unitList.push({
          key: 1,
          name: item.unit
        })
        item.unitList.push({
          key: 2,
          name: item.assistUnitA
        })
        item.unitList.push({
          key: 3,
          name: item.assistUnitB
        })
        item.number3 = item.number * item.convertRatioA;
        item.number4 = item.number * item.convertRatioB;
        // 重置unit
        if (item.defaultOutboundUnit !== null) {
          item.unit = item.unitList[item.defaultOutboundUnit - 1].key 
          this.changeUnit(item)
        }
        item.warehouseId = ''
        item.productId = item.id
        delete item.id
        if (item.inventoryFlag === '1') {
          if (this.currentType === 'productList') {
            productList.push(item)
            materialList.push(item)
          } else {
            materialList.push(item)
          }
        } else if (item.inventoryFlag === '0') {
          (this.currentType === 'productList' ? productList : materialList).push(item)
        } else {
          flag = true
        }
      })
      if (flag) {
        this.$message.error(
          '部分商品因未设置“参与库存计算”未保存成功！',
          3
        )
      }
      // 合计位置
      if (this.productList.length && this.productList[this.productList.length - 1][this.columns[0].dataIndex] === '合计') {
        this.productList.splice(this.productList.length - 1,0,...JSON.parse(JSON.stringify(productList)))
      }else{
        this.productList.push(...JSON.parse(JSON.stringify(productList)))
      }
      if (this.materialList.length && this.materialList[this.materialList.length - 1][this.columns2[0].dataIndex] === '合计') {
        this.materialList.splice(this.materialList.length - 1,0,...JSON.parse(JSON.stringify(materialList)))
      }else{
        this.materialList.push(...JSON.parse(JSON.stringify(materialList)))
      }
      this.countTotal()
    },
    countTotal() {
      const getTotal = (dataSource, key) => {
        return dataSource.reduce((pre, cur) => {
          return this.$toDecimal(pre + +cur[key])
        }, 0)
      }
      // // 合计
      // 1.产品明细
      if (this.productList.length) {
        if (this.productList[this.productList.length - 1][this.columns[0].dataIndex] === '合计') {
          this.productList.splice(this.productList.length - 1, 1)
          let item = {
            number: getTotal(this.productList, 'number'),
            amount: getTotal(this.productList, 'amount'),
            disabled: true,
            [this.columns[0].dataIndex]: '合计'
          }
          this.productList.push(item)
        } else {
          let item = {
            number: getTotal(this.productList, 'number'),
            amount: getTotal(this.productList, 'amount'),
            disabled: true,
            [this.columns[0].dataIndex]: '合计'
          }
          this.productList.push(item)
        }
      }
      // 物料明细

      if (this.materialList.length) {
        if (this.materialList[this.materialList.length - 1][this.columns2[0].dataIndex] === '合计') {
          this.materialList.splice(this.materialList.length - 1, 1)
          let item = {
            number: getTotal(this.materialList, 'number'),
            number3: getTotal(this.materialList, 'number3'),
            number4: getTotal(this.materialList, 'number4'),
            disabled: true,
            [this.columns2[0].dataIndex]: '合计'
          }
          this.materialList.push(item)
        } else {
          let item = {
            number: getTotal(this.materialList, 'number'),
            number3: getTotal(this.materialList, 'number3'),
            number4: getTotal(this.materialList, 'number4'),
            disabled: true,
            [this.columns2[0].dataIndex]: '合计'
          }
          this.materialList.push(item)
        }
      }
    },
    changePlan(record) {
      let res = this.form.planOptions.filter(item => item.id == record.planId);
      record.processCode = res[0].processCode
      record.standardHours = res[0].standardHours
      record.unitSalary = res[0].unitSalary
      this.$forceUpdate();
    },
    changeUnit(record) {
      if (record.unit == 1) {
        record.salePrice = +record.salePrice || (record.bizProduct && +record.bizProduct.salePrice) || 0
      } else if (record.unit == 2) {
        record.salePrice = +record.salePriceA || (record.bizProduct && +record.bizProduct.salePriceA) || 0
      } else if (record.unit == 3) {
        record.salePrice = +record.salePriceB || (record.bizProduct && +record.bizProduct.salePriceB) || 0;
      }
      record.price = record.salePrice;
      this.changeNumber(record);
    },
    changeNumber(record) {
      // if (record.unit == 1) {
      //   record.number = record.number;
      // } else if (record.unit == 2) {
      //   record.number = (record.number / record.bizProduct.convertRatioA).toFixed(3);
      // } else if (record.unit == 3) {
      //   record.number = (record.number / record.bizProduct.convertRatioB).toFixed(3);
      // }
      record.amount = ((record.price || 0) * +record.number * (record.coefficient || 1)).toFixed(4);
      this.$forceUpdate();
      this.countTotal()
    },
    changeNumber2(record) {
      record.number3 = (record.number * record.convertRatioA).toFixed(3);
      record.number4 = (record.number * record.convertRatioB).toFixed(3);
      this.countTotal()
      this.$forceUpdate();
    },
    handleChange(info, e) {
      const formData = new FormData();
      formData.append('file', info.file);
      upload(formData).then(response => {
        const d = {
          uid: info.file.uid,
          name: response.fileName,
          url: response.url,
          status: 'done'
        }
        this.fileList.push(d);
      })
    },
    handleRemove(info) {
      this.fileList = this.fileList.filter(function (item) {
        return item.uid != info.uid
      })
    },
    changeCustomer(e) {
      let item = this.customerIdOptions.find(v=>v.id === e)
      if(item){
        this.$set(this.form,'phone',item.phone)
        this.$set(this.form,'customernanObj',{ ids: item.customernan, names: item.customernanName } )
        
      }
      getBizCustomer(this.form.customerId).then(res => {
        this.form.isSettleSend = res.data.isClear;
        this.$forceUpdate();
      })
    },
    copy(item,index,type){
      
      this.$confirm({
        title: `确认复制?`,
        onOk:()=> {
          let parseItem = JSON.parse(JSON.stringify(item))
          parseItem.rowKey = randomUUID()
          if (type === 1) {
            this.productList.splice(index,0,parseItem)
          }else{
            this.materialList.splice(index,0,parseItem)
          }
        }
      })
    },
    deleteItem(item,index,type){
      this.$confirm({
        title: `确认删除?`,
        onOk:()=> {
          if (type === 1) {
            this.productList.splice(index,1)
          }else{
            this.materialList.splice(index,1)
          }
        }
      })
    },
    projectFocus(){
      console.log(666);
      this.$refs.BizProjectForm.show()
    },
    
    projectOk(rows){
      this.$set(this.form,'projectNumber',rows[0].projectNumber)
      this.$set(this.form,'projectId',rows[0].id)
    },
    handleSearch(value){
      if (this.handleTimer!== null) {
        clearTimeout(this.handleTimer)
      }
      this.handleTimer = setTimeout(()=>{
        this.getProjectList(value)
      },300);
    },
    getProjectList(value) {
      if (value === null || value === '') {
        return 
      }
      listBizProject({projectNumber:value}).then(response => {
        this.projectList = response.data.list
      })
    },
    
    /**
     * 设置table的row的class
     * @param {obj} row 
     * @param {number} index 
     */
     getRowClassName(row,index,type){
      let arr = this[type].filter(v=>v.productId === row.productId)
      if (arr.length > 1) {
        return 'multiple_table_row'
      }
    },
  }
}
